package com.guoguo.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.guoguo.base.PageBean;
import com.guoguo.entity.Images;
import com.guoguo.entity.UserExt;
import com.guoguo.entity.Users;
import com.guoguo.entity.vo.UserInfoVO;
import com.guoguo.entity.vo.UsersVO;
import com.guoguo.enums.AliOssImageEnum;
import com.guoguo.enums.RegexEnum;
import com.guoguo.mapper.ImagesMapper;
import com.guoguo.mapper.InviteRelationMapper;
import com.guoguo.mapper.UserExtMapper;
import com.guoguo.mapper.UsersMapper;
import com.guoguo.service.IUsersService;
import com.guoguo.service.UploadService;
import com.guoguo.utils.AliOssUtils;
import com.guoguo.utils.RedisUtils;
import com.guoguo.utils.StringUtils;
import com.guoguo.utils.UUIDUtils;
import com.guoguo.utils.aliOss.AliOssImage;
import com.guoguo.utils.aliOss.AliOssImageConfig;
import com.guoguo.utils.aliOss.AliOssImageConfigUtils;
import com.guoguo.utils.aliOss.AliOssImageFactory;

/**
 * Created by Administrator on 2017/8/7 0007.
 */
@Service
public class UsersServiceImpl implements IUsersService {
    //User接口
    @Autowired
    private UsersMapper usersMapper;

    //UserExtr接口
    @Autowired
    private UserExtMapper userExtMapper;

    @Autowired
    private InviteRelationMapper inviteRelationMapper;

    @Autowired
    private ImagesMapper imagesMapper;

    @Autowired
    private UploadService uploadService;

    private String newuserpwd;


    @Override
    public Users findUsers(String userName, String nickName, String icon, int appId, int phoneType) {
        //查询是否有第三方帐号存在
        Users users = null;
        String[] userNameArr = userName.split("_");
        if (userNameArr.length > 0) {
            Users temp = new Users();
            if ("qq".equals(userNameArr[0])) {
                temp.setQq(userName);
            } else if ("wx".equals(userNameArr[0])) {
                temp.setWebchat(userName);
            } else if ("wb".equals(userNameArr[0])) {
                temp.setWeibo(userName);
            } else {
                temp.setUsername(userName);
            }
            users = usersMapper.findAccount(temp);
        }
        //如果没有第三方帐号存在，则创建一个新的帐号
        if (users == null) {
            users = new Users();
            users.setUserId(UUIDUtils.getUUID());
            users.setUsername(userName);
            users.setNickname(nickName);
            users.setAppId(appId);
            users.setPhoneType(phoneType);
            usersMapper.insertUsers(users);

            UserExt userExt = new UserExt();
            userExt.setUserId(users.getUserId());
            userExt.setIcon(icon);

            Date date = new Date();
            userExt.setCreateTime(date);
            userExt.setRegistered(date);
            userExt.setLastTime(date);


            userExtMapper.insertUserExt(userExt);
        }
        return users;
    }

    @Override
    public Users findUser(String userName, String userpwd) {
        Users users = new Users();
        users.setUsername(userName);
        users.setUserpwd(userpwd);
        Users user = usersMapper.findUserAccount(users);
        return user;
    }

    @Override
    public boolean findUsers(String userName, String userpwd) {
        Users user = findUser(userName, userpwd);
        if (user != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Users findUserById(String userId) {
        Users users = usersMapper.selectByPrimaryKey(userId);
        return users;
    }

    @Override
    public UsersVO findUsersInfo(String userId) {
        UsersVO usersVO = usersMapper.findUsersInfo(userId);
        return usersVO;
    }

    @Override
    public UserInfoVO findUsersInfoVO(String userId) {
        UserInfoVO userInfoVO = usersMapper.findUsersInfoVO(userId);
        if (userInfoVO.getIcon() != null && !StringUtils.relace(userInfoVO.getIcon(), RegexEnum.IS_NET_URL.getValue())) {
//            AliOssImageConfig aliOssImageConfig = new AliOssImageConfig("test");
            userInfoVO.setIcon(AliOssUtils.getImageUrl(userInfoVO.getIcon()));//, aliOssImageConfig));
        }
        return userInfoVO;
    }

    @Override
    public void updateUsersInfo(Users users, UserExt userExt) {
        if (users != null) {
            usersMapper.updateUsers(users);
        }
        if (userExt != null) {
            userExtMapper.updateUserExt(userExt);
        }
    }

    /**
     * 用户注册
     */
    @Override
    public boolean userRegister(String username, String userpwd, String icon, String nickname, String appId) {
        //查看手机号码是否存在
        Users users = null;
        String[] usernames = username.split("");
        if (usernames.length > 0) {
            Users step = new Users();
            if ("phone".equals(usernames[0])) {
                users = usersMapper.findPhone(step);
            }
        }
        if (username == null) {
            users = new Users();
            UserExt userExt = new UserExt();
            users.setUsername(username);
            Date date = new Date();
            usersMapper.insertUsers(users);
        }
        return true;
    }

    /**
     * 找回密码
     *
     * @param username
     * @param userpwd
     * @param phone
     * @return
     */
    @Override
    public boolean updateUserpwd(String username, String userpwd, String phone) {

        //验证手机号是否正确

        if (StringUtils.isPhone("phone")) {
            if (phone.length() > 0) {
                Users user = new Users();
                user.setUserpwd(newuserpwd);
                usersMapper.insertUsers(user);
                return true;
            } else {
                return false;
            }
        }
        return false;

    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public PageBean<UsersVO> selectUserList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageBean<UsersVO>(usersMapper.selectUserList());
    }

    @Override
    public int insertUsers(Users users) {
        return usersMapper.insertUsers(users);

    }

    @Override
    public int updateUsers(Users users) {
        return usersMapper.updateUsers(users);

    }

    @Override
    public Users selectByPrimaryKey(String userId) {
        return usersMapper.selectByPrimaryKey(userId);
    }

    @Override
    public int count(String username) {
        return usersMapper.count(username);

    }


    /**
     * 游客登录
     *
     * @param Mac
     * @return
     */
    @Override
    public boolean guestLogin(String Mac) {
        if (Mac != null && "Mac".equals("Mac")) {
            RedisUtils redisUtils = RedisUtils.getInstance();
            redisUtils.set("Mac", Mac);
            return true;

        }
        return false;
    }

    /**
     * @Description：查询注册的用户是否被邀请过
     * @author: WYZ
     * @since: 2017年10月25日 下午7:18:46
     */
    @Override
    public String selectUserIsHaveSrcUser(String phone) {
        List<String> isHaveSrcUserList = new ArrayList<String>();
        String isHaveSrcUser = null;
        isHaveSrcUserList = inviteRelationMapper.selectUserIsHaveSrcUser(phone);
        if (isHaveSrcUserList.size() > 0 && isHaveSrcUserList != null) {
            isHaveSrcUser = isHaveSrcUserList.get(0);
        }
        return isHaveSrcUser;
    }

    /**  
	 * @Description： 邀请有奖
	 * @author: WYZ 
	 * @since: 2017年10月26日 下午8:28:29  
	 */
	@Override
	public Map<String, String> invitationAward(String userId, String imgId) {
		Map<String, String> data = new HashMap<String, String>();
		String waterImgUrl = null;
		String uploadQR = null;
		String albId = null;
		Images images = new Images();
		if (!StringUtils.isEmptyString(userId)) {
            Users users = usersMapper.selectByPrimaryKey(userId);
            if(users !=null){
            	data.put("username", users.getUsername());//用户名字
            	data.put("invitAcount", "0");//邀请人数
            	data.put("awardAcount", "0");//累计获得的金币奖励	
            }
            UserExt userExt = userExtMapper.findUserExt(userId);
            if(userExt != null){
            	data.put("icon", userExt.getIcon());//用户头像url
            }
        }
		if (!StringUtils.isEmptyString(imgId)) {
			images = imagesMapper.selectByPrimaryKey(imgId);
			if(images != null){
				data.put("imgDescription", images.getImgDescription());//图片描述
				data.put("originalUrl", images.getOriginalUrl());//图片url
				albId = images.getAlbId();
			}
		}else{
			images = imagesMapper.selectByPrimaryKeyOne();
			if(images != null){
				data.put("imgDescription", images.getImgDescription());//图片描述
				data.put("originalUrl", images.getOriginalUrl());//图片url
				albId = images.getAlbId();
			}
		}
		if (!StringUtils.isEmptyString(userId)) {
			uploadQR =  uploadService.uploadQRCode(userId,albId);
            data.put("uploadQR", uploadQR);//二维码
		}
		AliOssImageConfig aliOssImageConfig = AliOssImageConfigUtils.getWaterMark(data.get("uploadQR"),"水印图片", AliOssImageEnum.ALI_HANDLE_TEXT_WQY_MICROHEI.getValue());
	    AliOssImage abstractAliOssImage = AliOssImageFactory.createAliOssImage(aliOssImageConfig);
	    abstractAliOssImage.operatingString(aliOssImageConfig);
	    waterImgUrl = AliOssUtils.imageProcess(data.get("originalUrl"), aliOssImageConfig);
	    data.put("waterImgUrl", waterImgUrl);
		return data;
	}

}


